#! /usr/bin/env python
# -*- coding: utf-8 -*-

########################################################
# Part of MILIM NIRDAFOT project.
# Written by H. Magal, 2014
# See details on the project at the site:
#   https://sites.google.com/site/nirdafotdownloads/home
########################################################

# The basis for the list of words-lists is the files PLxxx.csv (after being processed by create_sorted_CSV_file.py)
# This file reads the outputNN.csv file, and it 'greps' in that file combinations given in the command line.

import codecs
import re
import sys

def Hebrew_re_Search (name, reStr):
    try:
        fin = codecs.open (filename=name, encoding='utf_16')
    except:
        print 'The file outputNN.csv cannot be opened. Does it exist ?'
        return

    sin = fin.readlines ()
    fin.close ()

    outlist = list ()
    for s in sin:                               # outer loop on lines of input file
        linelist = s.split (',')            # split into a list of words
        outlist.append (linelist)               # append line to whole list

    print 'RE string', reStr
    print 'RE matches'
    uStr = reStr.decode ('utf8')
    reObj = re.compile (uStr, re.UNICODE)       # compile string into a regex object
    for line in outlist:
        for word in line:
            found = reObj.search (word)         # search word for reObj
            if not found is None:
                for w in line:
                    if line.index (w) > len (line) - 3: # dont reverese words for last 2 items
                        r = w
                    else:
                        r = w [::-1]            # this operation REVERSES the word
                    print ' ' + r,
                break                           # break the for word in line: loop



########## main code ##########
if __name__ == '__main__':
    if len (sys.argv) < 2:
        print '   Usage: you must give some RE-Expression as 1st arg.'
        print '          Regex pattern can be ע.*ת to match AYIN,'
        print '            followed by 0 or more chars, then TAV'
    else:
        Hebrew_re_Search ('outputNN.csv', sys.argv[1])